
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @author Steven Suit
 * COSC 603
 * Project 1 Task 4
 * 
 */
public class stutter {

	public static String cu;
	public static String l;
	public static char c;
	
	/**
	 * Check for file passed in as argument,
	 * if not, use keyboard input
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException  {
		BufferedReader br = null;
		if (args.length == 0)
			Stut(new BufferedReader(new InputStreamReader(System.in)));
		else
			while (args.length > 0) {				
				br = new BufferedReader(new FileReader(args[0]));
				Stut(br);
				br.close();
				break;
			}
	}

	/**
	 * From the file passed in, check for duplicate words
	 * 
	 * @param input
	 * @throws IOException
	 */
	public static void Stut(BufferedReader input) throws IOException {;
		cu = new String();
		l = "\n";
		int ld = 1;
		int lc = 1;		
		int t = 0;
		
		while (true) {
			t = input.read();
			
			/**
			 * In order for Java to read to EOF when using read() iterate the loop 
			 * even when EOS is hit and run is a 'duplicate code'.  After this has 
			 * completed, check for the EOS flag -1, this will also indicate EOF.
			 */
			if ((char)t == '\r' || t == -1) 
				c = ' ';
			else 
				c = (char)t;
			
			if (String.valueOf(c).equals("\n"))
				lc++;

 			if (del() != 0) {
				if (ld != 0) 
					continue;
				ld = 1;
				if (cu.isEmpty())
					cu = "\n";
				else
					cu.concat("\n");
		
				if (same() != 0) {
					System.out.printf("Repeated word on line %d: %s %s\n", lc, l, cu);
					cu = new String();
				}
				else
					cp();
			}
			else {
				ld = 0;
				if (cu.equals("\n"))
					cu = String.valueOf(c);
				else
					cu = cu.concat(String.valueOf(c));
			}
 			
 			/**
 			 * Check to see if End Of Stream (EOS) has been reached
 			 */
 			if (t == -1)
				break;			
		}
		System.out.println();
	}

	/**
	 * Move the current word into the list
	 * and clear the current word.
	 */
	private static void cp() {
			l = cu;
			cu = new String();
	}

	/**
	 * Check the String 'array' to see if they are equal
	 * @return 0 (false) if not the same
	 * @return 1 (true) if the same
	 */
	private static int same() {
		if (!l.equals(cu) || (l.equals("\n") && cu.equals("\n")) )
			return 0;	
		return 1;
	}

	/**
	 * If one of these punctuation characters comes in,
	 * ignore it and move on
	 * @return 1 (true) if punctuation character found
	 * @return 0 (false) if not a punctuation
	 */
	private static int del() {
		char[] dels = {'\0', '\n', '	', ' ', ',', '.', '!', '-', '+', '=', ';', ':', '?', '&', '{', '}', '\\'};
	    int N = 17;
	    int i;
		
	    for (i = 0; i <= N-1; i++)
	    	if (c == dels [i])
	    		return 1;
	    return 0;
	}		
}
